package com.pingan.glue.gluegame.controller;

import com.pingan.glue.gluegame.common.ErrorMessage;
import com.pingan.glue.gluegame.common.utils.FileUtils;
import com.pingan.glue.gluegame.controller.form.FaceFieldForm;
import com.pingan.glue.gluegame.controller.form.FaceSearchForm;
import com.pingan.glue.gluegame.controller.form.ImageForm;
import com.pingan.glue.gluegame.controller.form.SearchResponse;
import com.pingan.glue.gluegame.entity.FaceFieldEntity;
import com.pingan.glue.gluegame.entity.FriendUserEntity;
import com.pingan.glue.gluegame.response.ResponseData;
import com.pingan.glue.gluegame.service.FaceService;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.UUID;

@Controller
@RequestMapping("face")
public class FaceController {

    private final static Logger LOGGER = LoggerFactory.getLogger(FaceController.class);

    @Value("${web.upload-path}")
    private String path;

    @Resource
    private FaceService faceService;

    @Resource
    private ResourceLoader resourceLoader;

    @PostMapping("detect")
    public @ResponseBody
    ResponseData<FaceFieldEntity> detect(@RequestParam("fileName") MultipartFile file,
                                         @RequestParam("token") String token){
        LOGGER.info("FaceController_detect: start");
        FriendUserEntity entity = (FriendUserEntity) SecurityUtils.getSubject().getPrincipal();
        String fileName = file.getOriginalFilename();
        String mobile = entity.getMobile();
        String uuid = UUID.randomUUID().toString();
        StringBuilder sb =new StringBuilder();
        StringBuilder fieldPath =new StringBuilder("/");
        Long userId = entity.getUserId();
        sb.append(path).append("/").append(mobile).append(uuid).append(fileName);
        fieldPath.append(mobile).append(uuid).append(fileName);
        String image = FileUtils.upload(file, sb.toString());
        FaceFieldEntity face = faceService.faceDetect(image,fieldPath.toString(),userId);
        return ResponseData.success(face);
    }

    @PostMapping("detect/base64")
    public @ResponseBody
    ResponseData<FaceFieldEntity> detectBase64(@RequestBody ImageForm form){
        LOGGER.info("FaceController_detectBase64: start");
        FriendUserEntity entity = (FriendUserEntity) SecurityUtils.getSubject().getPrincipal();
        String fileName = "detectBase64.jpg";
        String mobile = entity.getMobile();
        String uuid = UUID.randomUUID().toString();
        StringBuilder sb =new StringBuilder();
        StringBuilder fieldPath =new StringBuilder("/");
        Long userId = entity.getUserId();
        sb.append(path).append("/").append(mobile).append(uuid).append(fileName);
        fieldPath.append(mobile).append(uuid).append(fileName);
        FileUtils.upload(form, sb.toString());
        FaceFieldEntity face = faceService.faceDetect(form.getData(),fieldPath.toString(),userId);
        return ResponseData.success(face);
    }

    @PostMapping("add")
    public @ResponseBody
    ResponseData<String> add(@RequestBody FaceFieldForm form){
        LOGGER.info("FaceController_add: start");
        FriendUserEntity entity = (FriendUserEntity) SecurityUtils.getSubject().getPrincipal();
        String mobile = entity.getMobile();
        if (!entity.getUserId().equals(form.getUserId())){
            return ResponseData.error(ErrorMessage.FACE_ADD_USER_ID_ERROR);
        }
        form.setMobile(mobile);
        String face = faceService.add(form);
        return ResponseData.success(face);
    }

    @PostMapping("update")
    public @ResponseBody
    ResponseData<String> update(@RequestBody FaceFieldForm form,@RequestParam("token") String token){
        LOGGER.info("FaceController_update: start");
        FriendUserEntity entity = (FriendUserEntity) SecurityUtils.getSubject().getPrincipal();
        String mobile = entity.getMobile();
        if (!entity.getUserId().equals(form.getUserId())){
            return ResponseData.error(ErrorMessage.FACE_UPDATE_USER_ID_ERROR);
        }
        form.setMobile(mobile);
        String face = faceService.update(form);
        return ResponseData.success(face);
    }


    @PostMapping("search")
    public @ResponseBody
    ResponseData<SearchResponse> search(@RequestBody FaceSearchForm form){
        LOGGER.info("FaceController_search: start");
        FriendUserEntity entity = (FriendUserEntity) SecurityUtils.getSubject().getPrincipal();

        SearchResponse sr = faceService.faceSearch(form,entity);
        return ResponseData.success(sr);
    }


    /**
     * 显示单张图片
     * @return
     */
    @GetMapping("show/{fileName}")
    public void showPhotos(HttpServletResponse response, @PathVariable String fileName){
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");
        ServletOutputStream out =null;
        InputStream is =null;
        try {
            org.springframework.core.io.Resource res =  resourceLoader.getResource("file:" + path + fileName);
            out = response.getOutputStream();
            byte[] b =new byte[1024];
            int len;
            is = res.getInputStream();
            while ((len = is.read(b)) != -1){
                out.write(b,0,len);
            }
        } catch (Exception e) {
            return;
        }finally {
            closeStream(out, is);
        }
    }


    @PostMapping("excel")
    public @ResponseBody
    ResponseData<String> excel(@RequestParam("fileName") MultipartFile file, @RequestParam("token") String token){
        LOGGER.info("FaceController_excel: start");
        FriendUserEntity entity = (FriendUserEntity) SecurityUtils.getSubject().getPrincipal();
        String fileName = file.getOriginalFilename();
        String mobile = entity.getMobile();
        String uuid = UUID.randomUUID().toString();
        StringBuilder sb =new StringBuilder();
        StringBuilder fieldPath =new StringBuilder("/");
        sb.append(path).append("/").append(mobile).append(uuid).append(fileName);
        fieldPath.append(mobile).append(uuid).append(fileName);
        FileUtils.upload(file, sb.toString());
        faceService.excel(sb.toString());
        return ResponseData.success(null);
    }

    private void closeStream(ServletOutputStream out, InputStream is) {
        if(is !=null){
            try{
                is.close();
            }catch (Exception e){
                LOGGER.error("图片显示关闭输入流失败:",e);
            }
        }
        if(out !=null){
            try{
                out.close();
            }catch (Exception e){
                LOGGER.error("图片显示关闭输出流失败:",e);
            }
        }
    }
}
